﻿Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.Web.UI.Control

Partial Class WebForm_SelfManageWorkHeader_UploadFile
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Request.QueryString("NewTime") Is Nothing Then
            Response.Redirect(Request.RawUrl & "&NewTime=" & DateTime.Now.ToString("hhmmss"))
        End If

        Dim CasePassword As String = Request.QueryString("CasePassword")
        Dim UploadType As String = Request.QueryString("UploadType")
        SqlDataSource1.SelectParameters("CasePassword").DefaultValue = CasePassword
        SqlDataSource1.SelectParameters("UploadType").DefaultValue = UploadType
        SqlDataSource1.InsertParameters("CasePassword").DefaultValue = CasePassword
        SqlDataSource1.InsertParameters("UploadType").DefaultValue = UploadType

        If Not Me.IsPostBack Then
            '判斷目前使用者狀態
            Me.MyOrganizationID = clsAuth.GetOrganizationID(clsAuth.GetUserID())
            If clsAuth.IsEnvirPerson(MyOrganizationID) Then
                '環保局人員
                Me.MyType = "1"
            ElseIf clsAuth.IsRoadPerson(MyOrganizationID) Then
                '工務段人員
                Me.MyType = "3"
            ElseIf clsAuth.GetUserID() <> "" Then
                '公所人員
                Me.MyType = "2"
            Else
                '一般民眾
                Me.MyType = ""
            End If
        End If

        Dim HideItem As Boolean = False
        Dim HasInsert As Boolean = MyObj.HasInsert(CasePassword)
        '禁止上傳狀況如下：
        '(1)通報人開啟處理後照片
        '(2)通報人已完成通報後,查詢該案件,並開啟處理前照片
        '(3)公務段人員開啟處理前照片
        Select Case UploadType
            Case "PictureA"
                If Me.MyType = "" And HasInsert Then
                    HideItem = True
                ElseIf Me.MyType = "3" And HasInsert Then
                    HideItem = True
                End If
            Case "PictureB"
                If Me.MyType = "" Then
                    HideItem = True
                End If
        End Select

        If HasInsert Then
            Dim dat As New clsData
            Dim sql As New MyStringBuilder
            sql.AppendFormat("select * from FD_ActionRecord ")
            sql.AppendFormat("where Active='{0}' ", "Y")
            sql.AppendFormat("and CasePassword='{0}' ", CasePassword)
            sql.AppendFormat("and OrganizationID='{0}' ", Me.MyOrganizationID)
            If Not dat.GetData(sql.ToString()).Rows.Count > 0 Then
                HideItem = True
            End If
        End If

        If HideItem Then
            Panel1.Visible = False
            btnAdd.Visible = False
            hiFileUpload.Visible = False
            txtDesc.Visible = False
            GridView1.Columns(3).Visible = False
            GridView1.Columns(4).Visible = False
        End If
    End Sub

    Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles btnAdd.Click
        If Not Me.hiFileUpload.HasFile Then
            MyObj.ShowMessage("此上傳檔案不存在!!")
        ElseIf Check_File(hiFileUpload) Then
            Dim dat As New clsData
            Dim sql As New StringBuilder
            Dim dt As New Data.DataTable

            sql = sql.AppendFormat("select Count(*) as TotalCount,isnull(Sum(OriginalSize),0) as TotalSize from FD_UploadFile ")
            sql = sql.AppendFormat("where CasePassword='{0}' ", Request.QueryString("CasePassword"))
            sql = sql.AppendFormat("and UploadType='{0}' ", Request.QueryString("UploadType"))
            dt = dat.GetData(sql.ToString())

            If dt.Rows.Count > 0 Then
                If dt.Rows(0)("TotalCount") >= 8 Then
                    MyObj.ShowMessage("已超過圖片上傳總張數限制!!(8張)")
                ElseIf dt.Rows(0)("TotalSize") + hiFileUpload.PostedFile.ContentLength >= 3000000 Then
                    MyObj.ShowMessage("已超過圖片上傳總容量限制!!(3MB)")
                Else
                    Dim clsRandom As New clsRandom()
                    Dim FileName_New As String = DateTime.Today.Year & DateTime.Today.Month & DateTime.Today.Day & clsRandom.Generate(10) & ".jpg"
                    Dim sPath As String = Server.MapPath("~/") & "/public/UploadFile/" & FileName_New

                    If hiFileUpload.PostedFile.ContentLength >= 200000 Then '超過200k才壓縮
                        hiFileUpload.SaveAs(sPath & "Temp")
                        Me.ystp(sPath & "Temp", sPath)
                    Else
                        hiFileUpload.SaveAs(sPath)
                    End If

                    Using scope As New Transactions.TransactionScope
                        sql.Length = 0
                        sql.AppendFormat("insert FD_UploadFile (CasePassword,FileName_Old,FileName_New,FileDescription,OriginalSize,UploadType,CreateBy,CreateDay,UpdateBy,UpdateDay) select ")
                        sql.AppendFormat(" '{0}' ", Request.QueryString("CasePassword"))
                        sql.AppendFormat(",'{0}' ", hiFileUpload.FileName)
                        sql.AppendFormat(",'{0}' ", FileName_New)
                        sql.AppendFormat(",'{0}' ", Me.txtDesc.Text)
                        sql.AppendFormat(",{0} ", hiFileUpload.PostedFile.ContentLength)
                        sql.AppendFormat(",'{0}' ", Request.QueryString("UploadType"))
                        sql.AppendFormat(",'{0}' ", Me.User.Identity.Name)
                        sql.AppendFormat(",{0} ", "getdate()")
                        sql.AppendFormat(",'{0}' ", Me.User.Identity.Name)
                        sql.AppendFormat(",{0} ", "getdate()")
                        dat.AccData(sql)
                        scope.Complete()
                    End Using

                    Me.GridView1.DataBind()
                End If
            End If
        End If
    End Sub

    Protected Function Check_File(ByVal UploadFile As FileUpload) As Boolean
        If 1 = 2 And UploadFile.PostedFile.ContentType.ToString().ToUpper() <> "JPG" AndAlso UploadFile.PostedFile.ContentType.ToString().ToUpper() <> "PNG" Then
            MyObj.ShowMessage("上傳失敗!!請選擇副檔名(Jpg、Jpeg)檔案!!")
            Return False
            'ElseIf UploadFile.PostedFile.ContentLength > 204800 Then
            '    MyObj.ShowMessage("上傳失敗!!檔案不可超過200K!!")
            '    Return False
        Else
            Return True
        End If
    End Function

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles GridView1.RowDataBound
        If e.Row.RowType = DataControlRowType.DataRow Then
            TryCast(e.Row.FindControl("lblNo"), Label).Text = (GridView1.PageSize * GridView1.PageIndex) + e.Row.RowIndex + 1
            Dim Image1 As System.Web.UI.WebControls.Image = TryCast(e.Row.FindControl("Image1"), System.Web.UI.WebControls.Image)
            If Not Image1 Is Nothing Then
                Image1.Attributes("onclick") = "window.open('" + Image1.ImageUrl + "');"
            End If
            Dim hideCreateBy As HiddenField = TryCast(e.Row.FindControl("hideCreateBy"), HiddenField)
            If Not hideCreateBy Is Nothing Then
                If hideCreateBy.Value <> Me.User.Identity.Name Then
                    TryCast(e.Row.FindControl("LinkEdit"), LinkButton).Visible = False
                    TryCast(e.Row.FindControl("LinkDelete"), LinkButton).Visible = False
                End If
            End If
        End If
    End Sub

    Protected Sub GridView1_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles GridView1.RowUpdating
        Dim UploadFile As FileUpload = TryCast(GridView1.Rows(e.RowIndex).FindControl("hiFileUpload"), FileUpload)
        Dim hideFileName_Old As HiddenField = TryCast(GridView1.Rows(e.RowIndex).FindControl("hideFileName_Old"), HiddenField)
        Dim hideFileName_New As HiddenField = TryCast(GridView1.Rows(e.RowIndex).FindControl("hideFileName_New"), HiddenField)
        If UploadFile.FileName.Trim() = "" Then
            SqlDataSource1.UpdateParameters("FileName_Old").DefaultValue = hideFileName_Old.Value
            SqlDataSource1.UpdateParameters("FileName_New").DefaultValue = hideFileName_New.Value
        Else
            If Not UploadFile.HasFile Then
                MyObj.ShowMessage("此上傳檔案不存在!!")
                e.Cancel = True
            ElseIf Not Check_File(hiFileUpload) Then
                e.Cancel = True
            Else
                Dim clsRandom As New clsRandom()
                Dim FileName_New As String = DateTime.Today.Year & DateTime.Today.Month & DateTime.Today.Day & clsRandom.Generate(10) & ".jpg"
                Dim sPath As String = Server.MapPath("~/") & "/public/UploadFile/" & FileName_New
                Dim sPath_Del As String = Server.MapPath("~/") & "/public/UploadFile/" & hideFileName_New.Value

                If File.Exists(sPath_Del) Then
                    File.Delete(sPath_Del)
                End If

                If UploadFile.PostedFile.ContentLength >= 200000 Then '超過200k才壓縮
                    UploadFile.SaveAs(sPath & "Temp")
                    Me.ystp(sPath & "Temp", sPath)
                Else
                    UploadFile.SaveAs(sPath)
                End If

                SqlDataSource1.UpdateParameters("FileName_Old").DefaultValue = UploadFile.FileName
                SqlDataSource1.UpdateParameters("FileName_New").DefaultValue = FileName_New
                SqlDataSource1.UpdateParameters("UpdateBy").DefaultValue = Me.User.Identity.Name
            End If
        End If
    End Sub

    Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
        Dim hideFileName_New As HiddenField = TryCast(GridView1.Rows(e.RowIndex).FindControl("hideFileName_New"), HiddenField)
        Dim sPath_Del As String = Server.MapPath("~/") & "/public/UploadFile/" & hideFileName_New.Value

        If File.Exists(sPath_Del) Then
            File.Delete(sPath_Del)
        End If
    End Sub

    '登入者組織編號
    Public Property MyOrganizationID() As String
        Get
            Return ViewState("MyOrganizationID")
        End Get
        Set(ByVal value As String)
            ViewState("MyOrganizationID") = value
        End Set
    End Property

    '判斷登入者組織
    Public Property MyType() As String
        Get
            Return ViewState("MyType")
            '1:環保局
            '2:公所
            '3:工務段
        End Get
        Set(ByVal value As String)
            ViewState("MyType") = value
        End Set
    End Property

#Region "壓縮圖片"

    ''' <summary> 
    ''' 壓縮圖片 
    ''' </summary> 
    ''' <param name="filePath">要壓縮的圖片路徑</param> 
    ''' <param name="filePath_ystp">壓縮後的圖片路徑</param> 
    Public Sub ystp(ByVal filePath As String, ByVal filePath_ystp As String)
        'Bitmap 
        Dim bmp As Bitmap = Nothing

        'ImageCoderInfo 
        Dim ici As ImageCodecInfo = Nothing

        'Encoder 
        Dim ecd As Encoder = Nothing

        'EncoderParameter 
        Dim ept As EncoderParameter = Nothing

        'EncoderParameters 
        Dim eptS As EncoderParameters = Nothing

        Try
            bmp = New Bitmap(filePath)
            ici = Me.getImageCoderInfo("image/gif")

            ecd = Encoder.Quality

            eptS = New EncoderParameters(1)

            ept = New EncoderParameter(ecd, 10L)
            eptS.Param(0) = ept
            bmp.Save(filePath_ystp, ici, eptS)
        Catch ex As Exception
            Throw New Exception(ex.Message)
        Finally
            If bmp IsNot Nothing Then
                bmp.Dispose()
            End If
            If ept IsNot Nothing Then
                ept.Dispose()
            End If
            If eptS IsNot Nothing Then
                eptS.Dispose()
            End If
            File.Delete(filePath)
        End Try
    End Sub

    ''' <summary> 
    ''' 獲取圖片編碼類型信息 
    ''' </summary> 
    ''' <param name="coderType">編碼類型</param> 
    ''' <returns>ImageCodecInfo</returns> 
    Private Function getImageCoderInfo(ByVal coderType As String) As ImageCodecInfo
        Dim iciS As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()

        Dim retIci As ImageCodecInfo = Nothing

        For Each ici As ImageCodecInfo In iciS
            If ici.MimeType.Equals(coderType) Then
                retIci = ici
            End If
        Next

        Return retIci
    End Function

#End Region

End Class
